package com.ruoyi.service.quality.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.quality.MesQualityInspection;
import com.ruoyi.domain.purchase.MesPurchaseReceipt;
import com.ruoyi.domain.production.MesWorkOrder;
import com.ruoyi.mapper.quality.MesQualityInspectionMapper;
import com.ruoyi.service.quality.IMesQualityInspectionService;
import com.ruoyi.service.purchase.IMesPurchaseReceiptService;
import com.ruoyi.service.production.IMesWorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 质量检验记录Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class MesQualityInspectionServiceImpl implements IMesQualityInspectionService
{
    @Autowired
    private MesQualityInspectionMapper mesQualityInspectionMapper;
    
    @Autowired
    private IMesPurchaseReceiptService purchaseReceiptService;
    
    @Autowired
    private IMesWorkOrderService workOrderService;

    /**
     * 查询质量检验记录
     * 
     * @param inspectionId 质量检验记录主键
     * @return 质量检验记录
     */
    @Override
    public MesQualityInspection selectMesQualityInspectionByInspectionId(Long inspectionId)
    {
        return mesQualityInspectionMapper.selectMesQualityInspectionByInspectionId(inspectionId);
    }

    /**
     * 查询质量检验记录列表
     * 
     * @param mesQualityInspection 质量检验记录
     * @return 质量检验记录
     */
    @Override
    public List<MesQualityInspection> selectMesQualityInspectionList(MesQualityInspection mesQualityInspection)
    {
        return mesQualityInspectionMapper.selectMesQualityInspectionList(mesQualityInspection);
    }

    /**
     * 校验工艺路线编码是否唯一
     *
     * @param inspectionCode 工艺路线编码
     * @return 结果
     */
    @Override
    public String checkInspectionCodeUnique(String inspectionCode , Long inspectionId)
    {
        MesQualityInspection mesQualityInspection = mesQualityInspectionMapper.checkInspectionCodeUnique(inspectionCode,inspectionId);
        if (StringUtils.isNotNull(mesQualityInspection))
        {
            return "1"; // 编码已存在
        }
        return "0"; // 编码可用
    }

    /**
     * 根据工单ID查询检验记录列表
     * 
     * @param workOrderId 工单ID
     * @return 质量检验记录集合
     */
    @Override
    public List<MesQualityInspection> selectInspectionsByWorkOrderId(Long workOrderId)
    {
        return mesQualityInspectionMapper.selectInspectionsByWorkOrderId(workOrderId);
    }

    /**
     * 根据工单编号查询检验记录列表
     * 
     * @param workOrderCode 工单编号
     * @return 质量检验记录集合
     */
    @Override
    public List<MesQualityInspection> selectInspectionsByWorkOrderCode(String workOrderCode)
    {
        return mesQualityInspectionMapper.selectInspectionsByWorkOrderCode(workOrderCode);
    }

    /**
     * 根据检验类型查询检验记录列表
     * 
     * @param type 检验类型
     * @return 质量检验记录集合
     */
    @Override
    public List<MesQualityInspection> selectInspectionsByType(String type)
    {
        return mesQualityInspectionMapper.selectInspectionsByType(type);
    }

    /**
     * 根据检验员查询检验记录列表
     * 
     * @param inspector 检验员
     * @return 质量检验记录集合
     */
    @Override
    public List<MesQualityInspection> selectInspectionsByInspector(String inspector)
    {
        return mesQualityInspectionMapper.selectInspectionsByInspector(inspector);
    }

    /**
     * 根据状态查询检验记录列表
     * 
     * @param status 状态
     * @return 质量检验记录集合
     */
    @Override
    public List<MesQualityInspection> selectInspectionsByStatus(String status)
    {
        return mesQualityInspectionMapper.selectInspectionsByStatus(status);
    }

    /**
     * 新增质量检验记录
     * 
     * @param mesQualityInspection 质量检验记录
     * @return 结果
     */
    @Override
    public int insertMesQualityInspection(MesQualityInspection mesQualityInspection)
    {
        return mesQualityInspectionMapper.insertMesQualityInspection(mesQualityInspection);
    }

    /**
     * 修改质量检验记录
     * 
     * @param mesQualityInspection 质量检验记录
     * @return 结果
     */
    @Override
    public int updateMesQualityInspection(MesQualityInspection mesQualityInspection)
    {
        return mesQualityInspectionMapper.updateMesQualityInspection(mesQualityInspection);
    }

    /**
     * 批量删除质量检验记录
     * 
     * @param inspectionIds 需要删除的质量检验记录主键
     * @return 结果
     */
    @Override
    public int deleteMesQualityInspectionByInspectionIds(Long[] inspectionIds)
    {
        return mesQualityInspectionMapper.deleteMesQualityInspectionByInspectionIds(inspectionIds);
    }

    /**
     * 删除质量检验记录信息
     * 
     * @param inspectionId 质量检验记录主键
     * @return 结果
     */
    @Override
    public int deleteMesQualityInspectionByInspectionId(Long inspectionId)
    {
        return mesQualityInspectionMapper.deleteMesQualityInspectionByInspectionId(inspectionId);
    }

    // ==================== 采购入库质检(IQC)实现 ====================
    
    @Override
    @Transactional
    public MesQualityInspection createIQCInspection(Long receiptId, Long standardId) {
        // 获取入库单信息
        MesPurchaseReceipt receipt = purchaseReceiptService.selectMesPurchaseReceiptByReceiptId(receiptId);
        if (receipt == null) {
            throw new RuntimeException("入库单不存在");
        }
        
        // 检查是否已存在质检记录
        MesQualityInspection existingInspection = selectInspectionByReceiptId(receiptId);
        if (existingInspection != null) {
            throw new RuntimeException("该入库单已存在质检记录");
        }
        
        // 创建质检记录
        MesQualityInspection inspection = new MesQualityInspection();
        inspection.setInspectionCode(generateInspectionCode("IQC"));
        inspection.setInspectionType("IQC");
        inspection.setOrderId(receiptId); // 关联入库单ID
        inspection.setOrderCode(receipt.getReceiptCode());
        inspection.setStandardId(standardId);
        inspection.setInspectorId(SecurityUtils.getUserId());
        inspection.setInspectorName(SecurityUtils.getUsername());
        inspection.setInspectionDate(new Date());
        inspection.setStatus("PENDING"); // 待检验
        inspection.setCreateTime(DateUtils.getNowDate());
        inspection.setCreateBy(SecurityUtils.getUsername());
        
        // 保存质检记录
        mesQualityInspectionMapper.insertMesQualityInspection(inspection);
        
        // 更新入库单状态为待质检
        purchaseReceiptService.handleInspectionResult(receiptId, "PENDING");
        
        return inspection;
    }
    
    @Override
    @Transactional
    public int processIQCResult(Long inspectionId, String conclusion, String remark) {
        MesQualityInspection inspection = selectMesQualityInspectionByInspectionId(inspectionId);
        if (inspection == null) {
            throw new RuntimeException("质检记录不存在");
        }
        
        if (!"IQC".equals(inspection.getInspectionType())) {
            throw new RuntimeException("不是采购入库质检记录");
        }
        
        // 更新质检记录
        inspection.setConclusion(conclusion);
        inspection.setResult("PASS".equals(conclusion) ? "合格" : "不合格");
        inspection.setStatus("COMPLETED");
        inspection.setRemark(remark);
        inspection.setUpdateTime(DateUtils.getNowDate());
        inspection.setUpdateBy(SecurityUtils.getUsername());
        
        int result = mesQualityInspectionMapper.updateMesQualityInspection(inspection);
        
        // 处理入库单质检结果
        if (inspection.getOrderId() != null) {
            purchaseReceiptService.handleInspectionResult(inspection.getOrderId(), conclusion, remark);
        }
        
        return result;
    }
    
    @Override
    public MesQualityInspection selectInspectionByReceiptId(Long receiptId) {
        return mesQualityInspectionMapper.selectInspectionByReceiptId(receiptId);
    }
    
    // ==================== 制造过程质检(IPQC)实现 ====================
    
    @Override
    @Transactional
    public MesQualityInspection createIPQCInspection(Long workOrderId, Long processId, String inspectionType, Long standardId) {
        // 获取工单信息
        MesWorkOrder workOrder = workOrderService.selectMesWorkOrderByOrderId(workOrderId);
        if (workOrder == null) {
            throw new RuntimeException("工单不存在");
        }
        
        // 创建质检记录
        MesQualityInspection inspection = new MesQualityInspection();
        inspection.setInspectionCode(generateInspectionCode("IPQC"));
        inspection.setInspectionType("IPQC");
        inspection.setOrderId(workOrderId);
        inspection.setOrderCode(workOrder.getOrderCode());
        inspection.setProcessId(processId);
        inspection.setProductId(workOrder.getProductId());
        inspection.setProductCode(workOrder.getProductCode());
        inspection.setProductName(workOrder.getProductName());
        inspection.setStandardId(standardId);
        inspection.setInspectorId(SecurityUtils.getUserId());
        inspection.setInspectorName(SecurityUtils.getUsername());
        inspection.setInspectionDate(new Date());
        inspection.setStatus("PENDING");
        inspection.setRemark(inspectionType); // 记录检验类型(FIRST_PIECE/PATROL/LAST_PIECE)
        inspection.setCreateTime(DateUtils.getNowDate());
        inspection.setCreateBy(SecurityUtils.getUsername());
        
        return mesQualityInspectionMapper.insertMesQualityInspection(inspection) > 0 ? inspection : null;
    }
    
    @Override
    @Transactional
    public int processIPQCResult(Long inspectionId, String conclusion, String remark) {
        MesQualityInspection inspection = selectMesQualityInspectionByInspectionId(inspectionId);
        if (inspection == null) {
            throw new RuntimeException("质检记录不存在");
        }
        
        if (!"IPQC".equals(inspection.getInspectionType())) {
            throw new RuntimeException("不是制造过程质检记录");
        }
        
        // 更新质检记录
        inspection.setConclusion(conclusion);
        inspection.setResult("PASS".equals(conclusion) ? "合格" : "不合格");
        inspection.setStatus("COMPLETED");
        inspection.setRemark(remark);
        inspection.setUpdateTime(DateUtils.getNowDate());
        inspection.setUpdateBy(SecurityUtils.getUsername());
        
        int result = mesQualityInspectionMapper.updateMesQualityInspection(inspection);
        
        // 如果质检不通过，需要暂停工序生产
        if ("FAIL".equals(conclusion)) {
            // TODO: 调用生产模块API暂停工序
            // workOrderService.pauseProcess(inspection.getOrderId(), inspection.getProcessId());
        }
        
        return result;
    }
    
    @Override
    public List<MesQualityInspection> selectInspectionsByWorkOrderAndProcess(Long workOrderId, Long processId) {
        return mesQualityInspectionMapper.selectInspectionsByWorkOrderAndProcess(workOrderId, processId);
    }
    
    @Override
    public boolean canStartProcess(Long workOrderId, Long processId) {
        // 检查前序工序的质检是否通过
        List<MesQualityInspection> inspections = selectInspectionsByWorkOrderAndProcess(workOrderId, processId - 1);
        if (inspections.isEmpty()) {
            return true; // 第一道工序，可以开始
        }
        
        // 检查是否有质检不通过的记录
        return inspections.stream().noneMatch(inspection -> "FAIL".equals(inspection.getConclusion()));
    }
    
    // ==================== 制造成品质检(FQC)实现 ====================
    
    @Override
    @Transactional
    public MesQualityInspection createFQCInspection(Long workOrderId, Long productId, Long standardId) {
        // 获取工单信息
        MesWorkOrder workOrder = workOrderService.selectMesWorkOrderByOrderId(workOrderId);
        if (workOrder == null) {
            throw new RuntimeException("工单不存在");
        }
        
        // 检查是否已存在成品质检记录
        MesQualityInspection existingInspection = selectFQCInspectionByWorkOrderId(workOrderId);
        if (existingInspection != null) {
            throw new RuntimeException("该工单已存在成品质检记录");
        }
        
        // 创建质检记录
        MesQualityInspection inspection = new MesQualityInspection();
        inspection.setInspectionCode(generateInspectionCode("FQC"));
        inspection.setInspectionType("FQC");
        inspection.setOrderId(workOrderId);
        inspection.setOrderCode(workOrder.getOrderCode());
        inspection.setProductId(productId);
        inspection.setProductCode(workOrder.getProductCode());
        inspection.setProductName(workOrder.getProductName());
        inspection.setStandardId(standardId);
        inspection.setInspectorId(SecurityUtils.getUserId());
        inspection.setInspectorName(SecurityUtils.getUsername());
        inspection.setInspectionDate(new Date());
        inspection.setStatus("PENDING");
        inspection.setCreateTime(DateUtils.getNowDate());
        inspection.setCreateBy(SecurityUtils.getUsername());
        
        return mesQualityInspectionMapper.insertMesQualityInspection(inspection) > 0 ? inspection : null;
    }
    
    @Override
    @Transactional
    public int processFQCResult(Long inspectionId, String conclusion, String remark) {
        MesQualityInspection inspection = selectMesQualityInspectionByInspectionId(inspectionId);
        if (inspection == null) {
            throw new RuntimeException("质检记录不存在");
        }
        
        if (!"FQC".equals(inspection.getInspectionType())) {
            throw new RuntimeException("不是制造成品质检记录");
        }
        
        // 更新质检记录
        inspection.setConclusion(conclusion);
        inspection.setResult("PASS".equals(conclusion) ? "合格" : "不合格");
        inspection.setStatus("COMPLETED");
        inspection.setRemark(remark);
        inspection.setUpdateTime(DateUtils.getNowDate());
        inspection.setUpdateBy(SecurityUtils.getUsername());
        
        int result = mesQualityInspectionMapper.updateMesQualityInspection(inspection);
        
        // 更新工单状态
        if ("PASS".equals(conclusion)) {
            // TODO: 调用生产模块API更新工单为可完工状态
            // workOrderService.updateWorkOrderStatus(inspection.getOrderId(), "READY_TO_COMPLETE");
        } else {
            // TODO: 质检不通过，创建返工单或报废单
            // workOrderService.createReworkOrder(inspection.getOrderId());
        }
        
        return result;
    }
    
    @Override
    public MesQualityInspection selectFQCInspectionByWorkOrderId(Long workOrderId) {
        return mesQualityInspectionMapper.selectFQCInspectionByWorkOrderId(workOrderId);
    }
    
    @Override
    public boolean canCompleteWorkOrder(Long workOrderId) {
        MesQualityInspection fqcInspection = selectFQCInspectionByWorkOrderId(workOrderId);
        return fqcInspection != null && "PASS".equals(fqcInspection.getConclusion());
    }
    
    // ==================== 通用质检方法实现 ====================
    
    @Override
    public String generateInspectionCode(String inspectionType) {
        String prefix = inspectionType + DateUtils.dateTimeNow("yyyyMMdd");
        // 查询当天同类型质检记录数量
        int count = mesQualityInspectionMapper.countTodayInspectionsByType(inspectionType);
        return prefix + String.format("%03d", count + 1);
    }
    
    @Override
    @Transactional
    public int updateInspectionStatus(Long inspectionId, String targetStatus) {
        MesQualityInspection inspection = new MesQualityInspection();
        inspection.setInspectionId(inspectionId);
        inspection.setStatus(targetStatus);
        inspection.setUpdateTime(DateUtils.getNowDate());
        inspection.setUpdateBy(SecurityUtils.getUsername());
        
        return mesQualityInspectionMapper.updateMesQualityInspection(inspection);
    }
    
    @Override
    public Map<String, Object> getInspectionStatistics(String inspectionType, Date startDate, Date endDate) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 查询统计数据
        int totalCount = mesQualityInspectionMapper.countInspectionsByTypeAndDate(inspectionType, startDate, endDate);
        int passCount = mesQualityInspectionMapper.countPassInspectionsByTypeAndDate(inspectionType, startDate, endDate);
        int failCount = totalCount - passCount;
        
        statistics.put("totalCount", totalCount);
        statistics.put("passCount", passCount);
        statistics.put("failCount", failCount);
        statistics.put("passRate", totalCount > 0 ? (double) passCount / totalCount * 100 : 0);
        
        return statistics;
    }
}